<template>
  <div class="product-card" @click="handleClick">
    <!-- 骨架屏加载动画 -->
    <div v-if="loading" class="product-skeleton">
      <div class="skeleton-image"></div>
      <div class="skeleton-content">
        <div class="skeleton-line skeleton-title"></div>
        <div class="skeleton-line skeleton-price"></div>
        <div class="skeleton-line skeleton-info"></div>
        <div class="skeleton-line skeleton-actions"></div>
      </div>
    </div>
    
    <!-- 实际内容 -->
    <template v-else>
      <div class="image-container">
        <el-image 
          :src="product.imageUrl?.startsWith('http') ? product.imageUrl : `/api${product.imageUrl}`" 
          class="product-image"
          fit="cover"
          lazy
          @load="imageLoaded"
          @error="imageError"
        >
          <template #error>
            <div class="image-slot">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-image>
        <div class="product-badges">
          <div class="badge new" v-if="product.isNew">新品</div>
          <div class="badge discount" v-if="product.isDiscount==1">特惠</div>
        </div>
      </div>
      
      <div class="product-content">
        <h3 class="product-name">{{ product.name }}</h3>
        
        <div class="product-info">
          <div class="price-section">
            <div class="current-price">
              <span class="symbol">¥</span>
              <span class="amount">{{ product.isDiscount==1 ? product.discountPrice : product.price }}</span>
              <span class="original-price" v-if="product.isDiscount==1">¥{{ product.price }}</span>
            </div>
          </div>
          <div class="stock-info">
            <span class="stock" :class="{ 'low': product.stock < 10 }">
              库存: {{ product.stock }}
            </span>
            <span class="sales">已售{{ product.salesCount }}</span>
          </div>
          <div class="origin-info" v-if="product.placeOfOrigin">
            <el-icon><Location /></el-icon>
            <span>{{ product.placeOfOrigin }}</span>
          </div>
        </div>
        
        <div class="product-footer">
          <div class="action-group">
            <div class="favorite-btn" 
              :class="{ 'is-favorite': isFavoritePage || product.isFavorite }"
              @click.stop="handleFavorite">
              <el-icon>
                <component :is="isFavoritePage ? 'Delete' : (product.isFavorite ? 'StarFilled' : 'Star')" />
              </el-icon>
            </div>
            <div class="add-to-cart" @click.stop="handleAddToCart">
              <el-icon><ShoppingCart /></el-icon>
              <span>加入购物车</span>
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, defineProps, defineEmits } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import Request from '@/utils/request'

// 定义组件名称
defineOptions({
  name: 'ProductCard'
})

// 定义props
const props = defineProps({
  product: {
    type: Object,
    required: true
  },
  isFavoritePage: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emit = defineEmits(['add-to-cart', 'toggle-favorite'])

// 响应式数据
const userInfo = ref(JSON.parse(localStorage.getItem('frontUser') || '{}'))
const loading = ref(true)
const imageLoadedFlag = ref(false)
const router = useRouter()

// 图片加载完成
const imageLoaded = () => {
  // 移除延迟，图片加载完立即显示
  loading.value = false
}

// 图片加载失败
const imageError = () => {
  loading.value = false
}

// 检查是否登录
const isLogin = () => {
  // 检查是否登录
  const userStr = localStorage.getItem('frontUser')
  if (!userStr) {
    ElMessage({
      type: 'warning',
      message: '请先登录'
    })
    router.push('/login')
    return false
  }
  return true
}

// 添加到购物车
const handleAddToCart = async () => {
  try {
    if (!isLogin()) {
      return
    }

    const data = {
      userId: userInfo.value.id,
      productId: props.product.id,
      quantity: 1
    }

    const res = await Request.post('/cart', data)
    if (res.code === '0') {
      ElMessage({
        type: 'success',
        message: '已添加到购物车'
      })
      emit('add-to-cart', props.product)
    } else {
      ElMessage({
        type: 'error',
        message: res.msg || '添加失败'
      })
    }
  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage({
      type: 'error',
      message: '添加到购物车失败'
    })
  }
}

// 处理收藏
const handleFavorite = async () => {
  try {
    // 如果是在收藏页面，只触发事件
    if (props.isFavoritePage) {
      emit('toggle-favorite', props.product)
      return
    }

    if (!isLogin()) {
      return
    }

    const data = {
      userId: userInfo.value.id,
      productId: props.product.id,
      status: props.product.isFavorite ? 1 : 0
    }

    const res = await Request.post('/favorite', data)
    if (res.code === '0') {
      // 使用服务器返回的状态
      props.product.isFavorite = res.data.status === 1
      ElMessage({
        type: 'success',
        message: props.product.isFavorite ? '收藏成功' : '已取消收藏'
      })
      // 触发事件并传递最新状态
      emit('toggle-favorite', {
        product: props.product,
        status: res.data.status
      })

      // 重新获取收藏状态
      getFavoriteStatus()
    } else {
      ElMessage({
        type: 'error',
        message: res.msg || '操作失败'
      })
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage({
      type: 'error',
      message: '操作失败'
    })
  }
}

// 获取收藏状态的方法
const getFavoriteStatus = async () => {
  if (userInfo.value?.id) {
    try {
      const res = await Request.get(`/favorite/user/${userInfo.value.id}`)
      if (res.code === '0') {
        const favorites = res.data
        props.product.isFavorite = favorites.some(f => f.productId === props.product.id && f.status === 1)
      }
    } catch (error) {
      console.error('获取收藏状态失败:', error)
    }
  }
}

// 处理点击事件
const handleClick = () => {
  router.push(`/product/${props.product.id}`)
}

// 设置一个延迟结束加载状态的方法
const startLoading = () => {
  loading.value = true
  // 减少最大等待时间从2000ms到1000ms
  setTimeout(() => {
    loading.value = false
  }, 1000)
}

// 在created钩子之前添加图片预加载方法
const preloadImage = (src) => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.src = src
    img.onload = () => resolve(src)
    img.onerror = (err) => reject(err)
  })
}

// 生命周期钩子
onMounted(() => {
  startLoading()

  // 使用缓存的方式处理图片URL
  if (props.product.imageUrl) {
    const imgSrc = props.product.imageUrl.startsWith('http')
      ? props.product.imageUrl
      : `/api${props.product.imageUrl}`

    // 预加载图片
    preloadImage(imgSrc)
      .then(() => {
        loading.value = false // 预加载成功后直接关闭加载状态
      })
      .catch((error) => {
        console.error('图片预加载失败:', error)
        // 即使预加载失败，也通过startLoading中的超时机制最终关闭loading
      })
  }

  nextTick(() => {
    getFavoriteStatus()
  })
})
</script>

<style scoped>
.product-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  cursor: pointer;
  min-height: 350px; /* 设置最小高度以保持一致布局 */
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

/* 骨架屏样式 */
.product-skeleton {
  width: 100%;
  height: 100%;
  padding-bottom: 16px;
}

.skeleton-image {
  width: 100%;
  padding-bottom: 100%;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-content {
  padding: 12px;
}

.skeleton-line {
  height: 16px;
  margin-bottom: 12px;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 4px;
}

.skeleton-title {
  width: 80%;
  height: 18px;
}

.skeleton-price {
  width: 40%;
}

.skeleton-info {
  width: 65%;
}

.skeleton-actions {
  width: 100%;
  height: 32px;
  margin-top: 16px;
}

@keyframes shimmer {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

.image-container {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
  overflow: hidden;
  background: #f8f9fa;
}

.product-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transition: transform 0.4s ease;
}

.product-card:hover .product-image {
  transform: scale(1.05);
}

.product-badges {
  position: absolute;
  top: 8px;
  left: 8px;
  display: flex;
  gap: 6px;
  z-index: 1;
}

.badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: white;
}

.badge.new {
  background: rgba(103, 194, 58, 0.9);
}

.badge.discount {
  background: rgba(255, 71, 87, 0.9);
}

.product-content {
  padding: 12px;
}

.product-name {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
  color: #2c3e50;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 40px;
}

.product-info {
  margin-top: 8px;
}

.current-price {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.current-price .symbol {
  font-size: 12px;
  color: #ff4757;
}

.current-price .amount {
  font-size: 18px;
  font-weight: 600;
  color: #ff4757;
}

.original-price {
  color: #909399;
  font-size: 12px;
  text-decoration: line-through;
}

.stock-info {
  display: flex;
  justify-content: space-between;
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.stock {
  color: #67C23A;
}

.stock.low {
  color: #E6A23C;
}

.origin-info {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #606266;
  margin-top: 4px;
}

.origin-info :deep(.el-icon) {
  font-size: 14px;
  color: #67C23A;
}

.product-footer {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #f0f2f5;
}

.action-group {
  display: flex;
  gap: 8px;
}

.favorite-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  color: #909399;
  transition: all 0.3s ease;
  background: #f5f7fa;
}

.favorite-btn:hover {
  background: #f0f2f5;
}

.favorite-btn.is-favorite {
  color: #ff4757;
  background: rgba(255, 71, 87, 0.1);
}

.add-to-cart {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  background: #67C23A;
  color: white;
  padding: 8px;
  border-radius: 6px;
  font-size: 13px;
  transition: all 0.3s ease;
}

.add-to-cart:hover {
  background: #85ce61;
}

.add-to-cart :deep(.el-icon) {
  font-size: 14px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #909399;
  font-size: 20px;
  background: #f5f7fa;
}
</style>
